package co.flante.controllers;

import co.flante.entities.Event;
import co.flante.dao.EventManager;
import com.google.inject.Inject;
import play.libs.Json;
import play.mvc.BodyParser;
import play.mvc.Controller;
import play.mvc.Result;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title: Event Controller</p>
 * <p>Description: CRUD controller actions for events</p>
 * @author Mike Haas, Aaron Cook, Kyle Kolstad
 * @email michael.haas.@my.uwrf.edu, aaron.cook@my.uwrf.edu, kyle.kolstad@my.uwrf.edu
 * @date 11/25/2013
 */
public class EventController extends Controller {
    @Inject
    private EventManager eventManager;

    /**
     * Play Framework calls for a default constructor with Guice dependency injection
     */
    public EventController() {
    }

    /**
     * Get all events
     *
     * @return Result A json result with all events
     */
    public Result list() {
        List<Event> events = eventManager.findAll();

        if (events == null) {
            return ok(Json.toJson(new ArrayList<Event>()));
        }

        return ok(Json.toJson(events));
    }

    /**
     * Get an event identified by the id
     * @param id A unique Long identifying the event
     * @return A json result of the event as identified by id
     */
    public Result show(Long id) {
        Event event = eventManager.findById(id);

        if (event == null) {
            return notFound();
        }

        return ok(Json.toJson(event));
    }

    /**
     * Creates an event by parsing the body of the POST request as json.
     * As per HTTP spec it returns a created 201 and sets the Location header to the location of the created event.
     * @return result of created with no body
     */
    @BodyParser.Of(BodyParser.Json.class)
    public Result create() {
        Event event = Json.fromJson(request().body().asJson(), Event.class);
        eventManager.create(event);

        response().setHeader("Location", routes.EventController.list().absoluteURL(request()));

        return created();
    }
}